package com.youlin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.youlin.dto.BaseDataResDto;
import com.youlin.dto.BaseResDto;
import com.youlin.dto.Status;
import com.youlin.entities.BygUndertaker;
import com.youlin.mapper.BygUndertakerMapper;
import com.youlin.service.BygUndertakerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlin.untils.Md5Util;
import com.youlin.untils.RedisUtil;
import com.youlin.untils.SMSUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service
public class BygUndertakerServiceImpl extends ServiceImpl<BygUndertakerMapper, BygUndertaker> implements BygUndertakerService {

    @Autowired
    private SMSUtil smsUtil;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public BygUndertaker findTaker (String name, String tel) {
        if (StringUtils.isBlank(name) && StringUtils.isBlank(tel)) return null;
        QueryWrapper<BygUndertaker> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) queryWrapper.eq("name", name);
        if (StringUtils.isNotBlank(tel)) queryWrapper.eq("tel", tel);
        return getOne(queryWrapper);
    }

    @Override
    public BaseDataResDto<String> takerLogin(String tel, Integer code) {
        Integer redisCode = RedisUtil.getObject(redisTemplate, "tel:" + tel, Integer.class);
        if (redisCode == null) return new BaseDataResDto<>(Status.CODEINVALID);
        if (! redisCode.equals(code)) return new BaseDataResDto<>(Status.CODEERROR);
        String takerToken = Md5Util.getUUID();
        RedisUtil.setObjectExpire(redisTemplate, "takerToken:" + takerToken, null);
        return new BaseDataResDto<String>(Status.SUCCESS).setData(takerToken);
    }

    @Override
    public BaseResDto sendCode(String tel) {
        if (redisTemplate.hasKey("tel:"+tel)) return new BaseResDto(Status.SENDCODEERROR);
        LambdaQueryWrapper<BygUndertaker> wrapper = Wrappers.lambdaQuery(BygUndertaker.class)
                .eq(BygUndertaker::getTel, tel).last("LIMIT 1");
        if (getOne(wrapper) == null) return new BaseResDto(Status.PARAMETERERROR);
        JSONObject jsonObject = smsUtil.sendSms(tel, SMSUtil.Template.TAKERLOGIN);
        Integer code = jsonObject.getInteger("code");
        RedisUtil.setObjectExpire(redisTemplate, "tel:"+tel, code, 60L, TimeUnit.SECONDS);
        return new BaseResDto(Status.SUCCESS);
    }

}
